package com.example.ercmssystem2.repository;

import com.example.ercmssystem2.entity.Notification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

@Repository
public interface NotificationRepository extends JpaRepository<Notification, Long> {
    
    // 根据用户ID查询通知
    List<Notification> findByUserIdOrderByCreatedAtDesc(Long userId);
    
    // 根据用户ID和已读状态查询通知
    List<Notification> findByUserIdAndReadOrderByCreatedAtDesc(Long userId, Boolean read);
    
    // 查询用户未读通知数量
    @Query("SELECT COUNT(n) FROM Notification n WHERE n.user.id = :userId AND n.read = false")
    Long countUnreadByUserId(@Param("userId") Long userId);
    
    // 根据事件ID查询通知
    List<Notification> findByEventIdOrderByCreatedAtDesc(Long eventId);
    
    // 根据类型查询通知
    List<Notification> findByTypeOrderByCreatedAtDesc(String type);
    
    // 根据时间范围查询通知
    List<Notification> findByCreatedAtBetweenOrderByCreatedAtDesc(LocalDateTime start, LocalDateTime end);
    
    // 查询用户最近的通知
    @Query("SELECT n FROM Notification n WHERE n.user.id = :userId ORDER BY n.createdAt DESC")
    List<Notification> findRecentByUserId(@Param("userId") Long userId);
    
    // 标记用户所有通知为已读
    @Modifying
    @Query("UPDATE Notification n SET n.read = true, n.readAt = :readAt WHERE n.user.id = :userId AND n.read = false")
    void markAllAsReadByUserId(@Param("userId") Long userId, @Param("readAt") LocalDateTime readAt);
    
    // 删除旧通知
    @Modifying
    @Query("DELETE FROM Notification n WHERE n.createdAt < :beforeDate")
    void deleteOldNotifications(@Param("beforeDate") LocalDateTime beforeDate);
    
    // 根据优先级查询通知
    List<Notification> findByPriorityOrderByCreatedAtDesc(String priority);
    
    // 查询紧急通知
    @Query("SELECT n FROM Notification n WHERE n.isUrgent = true ORDER BY n.createdAt DESC")
    List<Notification> findUrgentNotifications();
    
    // 查询需要确认的通知
    @Query("SELECT n FROM Notification n WHERE n.requiresAcknowledgment = true AND n.read = false ORDER BY n.createdAt DESC")
    List<Notification> findNotificationsRequiringAcknowledgment();
    
    // 根据用户ID和类型查询通知
    List<Notification> findByUserIdAndTypeOrderByCreatedAtDesc(Long userId, String type);
    
    // 查询用户未确认的通知数量
    @Query("SELECT COUNT(n) FROM Notification n WHERE n.user.id = :userId AND n.requiresAcknowledgment = true AND n.acknowledgedAt IS NULL")
    Long countUnacknowledgedByUserId(@Param("userId") Long userId);
} 